#import "ItemsDNDController.h"
#import "Item.h"

@implementation ItemsDNDController

- (void)awakeFromNib
{
	NSArray *dragTypes = [NSArray arrayWithObjects:NSFilenamesPboardType, nil];
	[tableView registerForDraggedTypes:dragTypes];
	
	[super awakeFromNib];
}

//- (BOOL)tableView:(NSTableView *)tv writeRows:(NSArray*)rows
- (NSDragOperation)tableView:(NSTableView*)tv validateDrop:(id <NSDraggingInfo>)info proposedRow:(int)row
	proposedDropOperation:(NSTableViewDropOperation)op
{
	NSDragOperation dragOp = NSDragOperationCopy;
	[tv setDropRow:row dropOperation:NSTableViewDropAbove];
	
	return dragOp;
}

- (BOOL)tableView:(NSTableView*)tv
	   acceptDrop:(id <NSDraggingInfo>)info
			  row:(int)row
	dropOperation:(NSTableViewDropOperation)op
{

	Item* newObj = NULL;

	// Determine the type of object that was dropped
	NSArray *supportedtypes = [NSArray arrayWithObjects:NSFilenamesPboardType, nil];
	NSPasteboard *pboard = [info draggingPasteboard];
	NSString *bestType = [pboard availableTypeFromArray:supportedtypes];
	
	// Handle dropped files
	if ([bestType isEqualToString:NSFilenamesPboardType])
	{
		NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
		NSMutableArray *items = [NSMutableArray array];
		
		int i;
		for (i = 0; i < [files count]; i++)
		{
			newObj = [self newObject];
			[newObj setFile:[files objectAtIndex:i]];
			[items addObject:newObj];
		}
		
		[self addObjects:items];
		
		return TRUE;

	}
	
	return FALSE;
}

@end
